package erz.printing.police;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import erz.printing.police.adapter.TakePhotoAdapter;
import erz.printing.police.print.PhotoPrintAdapter;
import me.iwf.photopicker.PhotoPicker;

public class PrintPhotoActivity extends BaseActivity implements View.OnClickListener {
    private GridView gridView;
    private TakePhotoAdapter gridAdapter;
    private Button printBtn;
    private Button noticeBtn;
    private Button punishmentBtn;
    private EditText danweiEt;
    private TextView dateTv;
    private TextView tailTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_photo);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        fixPlaceHolderHeight();

        initView();
    }

    private void fixPlaceHolderHeight() {
        int height = getActionBarHeight() + getStatusBarHeight();
        View view = findViewById(R.id.place_holder);
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        lp.height = height;
        view.setLayoutParams(lp);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initView() {
        gridView = findViewById(R.id.images_gridView);
        gridAdapter = new TakePhotoAdapter(new ArrayList<String>(), this, 0);
        gridView.setAdapter(gridAdapter);
        gridView.setSelector(new ColorDrawable(0));

        printBtn = findViewById(R.id.photo_print);
        printBtn.setOnClickListener(this);
        noticeBtn = findViewById(R.id.notice_print);
        noticeBtn.setOnClickListener(this);
        punishmentBtn = findViewById(R.id.punishment_print);
        punishmentBtn.setOnClickListener(this);

        danweiEt = findViewById(R.id.danwei);
        dateTv = findViewById(R.id.ff_check_date);
        tailTv = findViewById(R.id.title_tail);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String checkTitle = bundle.getString("checkTitle");
            if (checkTitle != null) {
                tailTv.setText(checkTitle);
            }
            String noticeName = bundle.getString("noticeName");
            noticeBtn.setText(noticeName);

            String punishmentName = bundle.getString("punishmentName");
            if (punishmentName != null && punishmentName.length() > 0) {
                punishmentBtn.setText(punishmentName);
                punishmentBtn.setVisibility(View.VISIBLE);
                findViewById(R.id.last_placeholder).setVisibility(View.VISIBLE);

                adjustButtonWidth(3);
            } else {
                punishmentBtn.setVisibility(View.GONE);
                findViewById(R.id.last_placeholder).setVisibility(View.GONE);
                adjustButtonWidth(2);
            }

            String title = bundle.getString("title", "警务快打");
            ActionBar actionBar = getSupportActionBar();
            actionBar.setTitle(title);
        }
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        dateTv.setText(sdf.format(date));
    }

    private void adjustButtonWidth(int count) {
        Button[] btns = {printBtn, noticeBtn, punishmentBtn};
        int[] cs = new int[3];
        int total = 0;
        for (int i = 0; i < count; i++) {
            cs[i] = btns[i].getText().length();
            total += cs[i];
        }
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int w = width - (4 - count) * 10 * count;

        for (int i = 0; i < count && i < btns.length; i++) {
            ViewGroup.LayoutParams lp = btns[i].getLayoutParams();
            lp.width = (int)(w * cs[i] * 1.0f / total);
            btns[i].setLayoutParams(lp);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                gridAdapter.addPhotos(photos);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.photo_print) {
            doPrintPhoto();
        }
        else if (v.getId() == R.id.notice_print) {
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            String docTemplate = bundle.getString("docTemplateNotice");

            Intent newIntent = new Intent(this, DocumentActivity.class);
            Bundle newBundle = new Bundle();
            if (docTemplate != null) {
                newBundle.putString("docTemplate", docTemplate);
            }
            String title = bundle.getString("title", "");
            title += "-" + ((Button)v).getText();
            newBundle.putString("title", title);

            newIntent.putExtras(newBundle);
            startActivity(newIntent);
        }
        else if (v.getId() == R.id.punishment_print) {
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            String docTemplate = bundle.getString("docTemplatePunishment");

            Intent newIntent = new Intent(this, DocumentActivity.class);
            Bundle newBundle = new Bundle();
            if (docTemplate != null) {
                newBundle.putString("docTemplate", docTemplate);
            }
            String title = bundle.getString("title", "");
            title += "-" + ((Button)v).getText();
            newBundle.putString("title", title);

            newIntent.putExtras(newBundle);
            startActivity(newIntent);
        }
    }

    private void doPrintPhoto() {
        if (gridAdapter.getPhotos().size() == 0) {
            Toast.makeText(this, "请添加照片", Toast.LENGTH_SHORT).show();
            return;
        }
        // Get a PrintManager instance
        PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
        // Set job name, which will be displayed in the print queue
        String jobName = "打印现场照片";
        // Start a print job, passing in a PrintDocumentAdapter implementation
        // to handle the generation of a print document
        PhotoPrintAdapter printAdapter = new PhotoPrintAdapter(this);
        printAdapter.setSubTitle(makePrintSubtitle());
        printAdapter.setPhotos(gridAdapter.getPhotos());

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            printAdapter.setShowExaminer(bundle.getBoolean("printExaminer", false));
            printAdapter.setShowTitle(bundle.getBoolean("printTitle", false));
        }

        printManager.print(jobName, printAdapter, null); //
    }

    private String makePrintSubtitle() {
        String strDate = dateTv.getText().toString();
        String str = danweiEt.getText().toString();
        String tail = tailTv.getText().toString();
        return strDate + str + tail;
    }
}
